#import "CTBasicVC.h"
#import "CTInfoCell.h"
#import "CTRowData.h"
#import "CTSectionData.h"
#import "TJPickerView.h"
#import "CTHeaderTitleView.h"
#import "CTSexCell.h"
#import "NSDate+BRPickerView.h"
#import "CTBasicTableFooter.h"
#import "CTHomeVC.h"
@interface CTBasicVC () <UITableViewDelegate,UITableViewDataSource,UITabBarControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic ,strong) UIButton *nextButton;
@property (nonatomic ,strong) CTBasicTableFooter *tableFooter;
@end
@implementation CTBasicVC
- (void)zj_viewWillDisappearForIndex:(NSInteger)index {
    [self.view endEditing:YES];
}
- (void)zj_viewWillAppearForIndex:(NSInteger)index {
    self.pageIndex = index;
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kct_page_idcard,
        @"elementUniqueIdentifier"  : kct_page_idcard,
        @"referenceIdentification" : @"",
    };
    [CTUploadManager ct_uploadType:CTUploadTypePage data:data];
    if (!beNil(self.pageModel.operationalTaskID)) {
        NSDictionary *credtiData = @{
            @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
            @"errorFlag" : kcredit_point_idcard,
        };
        [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
    }
}
- (void)setPageModel:(CTPageElementModel *)pageModel {
    _pageModel = pageModel;
    if (!beNil(self.pageModel.operationalTaskID)) {
        NSDictionary *credtiData = @{
            @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
            @"errorFlag" : kcredit_point_idcard,
        };
        [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self listConfig];
    [self setUI];
}
- (void)setUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.nextButton];
}
- (void)listConfig{
    CTRowData * firstName = [CTRowData new];
    firstName.tfModel = [[CTTFModel alloc] init];
    firstName.editType = CTCellTypeFirstName;
    firstName.placeHolder = @"Please enter first name";
    CTSectionData *section1 = [[CTSectionData alloc] init];
    section1.sectionTitle = @"firstName";
    [section1.sectionData addObject:firstName];
    CTRowData * middleName = [CTRowData new];
    middleName.tfModel = [[CTTFModel alloc] init];
    middleName.editType = CTCellTypeMiddleName;
    middleName.placeHolder = @"Please enter middle name";
    CTSectionData *section2 = [[CTSectionData alloc] init];
    section2.sectionTitle = @"Middle name(Optional)";
    [section2.sectionData addObject:middleName];
    CTRowData * lastName = [CTRowData new];
    lastName.tfModel = [[CTTFModel alloc] init];
    lastName.editType = CTCellTypeLastName;
    lastName.placeHolder = @"Please enter last name";
    CTSectionData *section3 = [[CTSectionData alloc] init];
    section3.sectionTitle = @"Last name";
    [section3.sectionData addObject:lastName];
    CTRowData * birthday = [CTRowData new];
    birthday.editType = CTCellTypeBirthday;
    birthday.selector = @"selectBirthday";
    birthday.placeHolder = @"Please select date of birth";
    CTSectionData *section4 = [[CTSectionData alloc] init];
    section4.sectionTitle = @"Date of birth";
    [section4.sectionData addObject:birthday];
    CTRowData * sex = [CTRowData new];
    sex.editType = CTCellTypeSex;
    CTSectionData *section5 = [[CTSectionData alloc] init];
    section5.sectionTitle = @"Gender";
    [section5.sectionData addObject:sex];
    CTRowData * bvn = [CTRowData new];
    bvn.tfModel = [[CTTFModel alloc] init];
    bvn.editType = CTCellTypeBVN;
    bvn.placeHolder = @"please input your BVN";
    CTSectionData *section6 = [[CTSectionData alloc] init];
    section6.sectionTitle = @"BVN";
    [section6.sectionData addObject:bvn];
    [self.dataArray addObject:section1];
    [self.dataArray addObject:section2];
    [self.dataArray addObject:section3];
    [self.dataArray addObject:section4];
    [self.dataArray addObject:section5];
    [self.dataArray addObject:section6];
}
#pragma mark - Action
- (void)selectBirthdayClick:(NSIndexPath *)indexPath {
    __weak typeof(self) weakself = self;
    TJPickerView *picker = [[TJPickerView alloc] initWithTitle:@"Birthday" pickerMode:BRDatePickerModeYMD minDate:nil maxDate:[NSDate date] completion:^(NSDate *selectDate, NSString *selectValue) {
        CTSectionData *sectionModel = self.dataArray[indexPath.section];
        CTRowData *model = sectionModel.sectionData[indexPath.row];
        NSString *dateStr = [NSDate br_getDateString:selectDate format:@"dd/MM/yyyy"];
        model.content = dateStr;
        weakself.model.birthCelebrationDate = dateStr;
        [weakself.tableView reloadData];
    }];
    [picker show];
}
#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CTSectionData *sectionModel = self.dataArray[section];
    return sectionModel.sectionData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTSectionData *sectionModel = self.dataArray[indexPath.section];
    CTRowData *rowModel = sectionModel.sectionData[indexPath.row];
    CTInfoCell *cell = [CTInfoCell cellForTableView:tableView];
    cell.cellType = rowModel.editType;
    if (!beNil(rowModel.placeHolder)) {
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:rowModel.placeHolder attributes:
        @{NSForegroundColorAttributeName:[UIColor color999]}];
        cell.contentTF.attributedPlaceholder = attrString;
    }
    __weak typeof(self) weakSelf = self;
    switch (rowModel.editType) {
        case CTCellTypeFirstName: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.familyNameDesignation;
            cell.contentTF.keyboardType = UIKeyboardTypeDefault;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                weakSelf.model.familyNameDesignation = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_idcard_firstname;
                tfModel.elementUniqueIdentifier = kct_tf_idcard_firstname;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeMiddleName: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.middle_name;
            cell.contentTF.keyboardType = UIKeyboardTypeDefault;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                weakSelf.model.middle_name = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_idcard_midname;
                tfModel.elementUniqueIdentifier = kct_tf_idcard_midname;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeLastName: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.additionalName;
            cell.contentTF.keyboardType = UIKeyboardTypeDefault;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                weakSelf.model.additionalName = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_tf_idcard_lastname;
                tfModel.elementUniqueIdentifier = kct_tf_idcard_lastname;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeBVN: {
            cell.tfModel = rowModel.tfModel;
            cell.contentTF.text = self.model.bankVerificationDetail;
            cell.contentTF.keyboardType = UIKeyboardTypeNumberPad;
            cell.editingBlock = ^(CTInfoCell * _Nonnull cell, NSString * _Nonnull content) {
                if (content.length > 11) {
                    content = [content substringWithRange:NSMakeRange(0, 11)];
                    cell.contentTF.text = [content substringWithRange:NSMakeRange(0, 11)];
                }
                weakSelf.model.bankVerificationDetail = content;
            };
            cell.editDidEndBlock = ^(CTInfoCell * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
                tfModel.navigationRoute = NSStringFromClass(self.class);
                tfModel.pageIdentity = kct_ft_idcard_bvn_number;
                tfModel.elementUniqueIdentifier = kct_ft_idcard_bvn_number;
                rowModel.tfModel = tfModel;
                NSDictionary *data = [tfModel model_keyValues];
                [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
            };
        }
            break;
        case CTCellTypeSex: {
            CTSexCell *cell = [CTSexCell cellForTableView:tableView];
            cell.gender = self.model.demographicSex;
            cell.selectBlock = ^(NSString * _Nonnull selectValue) {
                rowModel.content = selectValue;
                weakSelf.model.demographicSex = selectValue;
            };
            return cell;
        }
            break;
        case CTCellTypeBirthday: {
            cell.contentTF.text = self.model.birthCelebrationDate;
        }
            break;
        default:
            break;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Ratio(54);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CTHeaderTitleView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CTHeaderTitleView"];
    CTSectionData *sectionModel = self.dataArray[section];
    header.titleLabel.text = sectionModel.sectionTitle;
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return Ratio(34);
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [[UIView alloc] init];
    footer.backgroundColor = [UIColor color202020];
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTSectionData *sectionModel = self.dataArray[indexPath.section];
    CTRowData *model = sectionModel.sectionData[indexPath.row];
    NSString *selector = model.selector;
    if ([selector isEqualToString:@"selectBirthday"]) {
        [self selectBirthdayClick:indexPath];
        NSDictionary *data = @{
            @"navigationRoute" : NSStringFromClass(self.class),
            @"pageIdentity" : kct_btn_idcard_birthday,
            @"elementUniqueIdentifier"  : kct_btn_idcard_birthday,
        };
        [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
    }
}
#pragma mark - setting && getting
- (UITableView *)tableView
{
    if (_tableView==nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-Ratio(20), [UIDevice ct_viewHeight]-Ratio(66) - Ratio(90) - [UIDevice ct_safeBottom]) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[CTHeaderTitleView class] forHeaderFooterViewReuseIdentifier:@"CTHeaderTitleView"];
        _tableView.tableFooterView = self.tableFooter;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
        }
    }
    return _tableView;
}
- (CTBasicTableFooter *)tableFooter {
    if (!_tableFooter) {
        _tableFooter = [[CTBasicTableFooter alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, Ratio(150))];
    }
    return _tableFooter;
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UIButton *)nextButton
{
    if (!_nextButton) {
        _nextButton = [[UIButton alloc] init];
        _nextButton.frame = CGRectMake((Ratio(10)), self.tableView.ct_bottom + Ratio(20),kScreenWidth - Ratio(40), Ratio(50));
        [_nextButton setBackgroundColor:[UIColor colorFF6C2E]];
        [_nextButton setTitleColor: [UIColor colorFFF] forState:UIControlStateNormal];
        _nextButton.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:Ratio(20)];
        [_nextButton setTitle:@"Next" forState:UIControlStateNormal];
        _nextButton.layer.cornerRadius = Ratio(10);
        _nextButton.layer.masksToBounds = YES;
        [_nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}
- (void)nextFailPoint {
    NSDictionary *credtiData = @{
        @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
        @"errorFlag" : kpage_idcard_nextFailPoint,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
}
- (void)nextButtonClick {
    if (![self.model.familyNameDesignation isNameFormated] || ![self.model.additionalName isNameFormated]) {
        [self.view showText:@"The name format is incorrect"];
        [self nextFailPoint];
        return;
    }
    if (beNil(self.model.birthCelebrationDate)) {
        [self.view showText:@"Please select birthday"];
        [self nextFailPoint];
        return;
    }
    if (beNil(self.model.demographicSex)) {
        [self.view showText:@"Please select gender"];
        [self nextFailPoint];
        return;
    }
    if (![self.model.bankVerificationDetail isBVNFormated]) {
        [self.view showText:@"Please enter the correct ID number"];
        [self nextFailPoint];
        return;
    }
    NSDictionary *basicData = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kct_btn_idcard_next,
        @"elementUniqueIdentifier"  : kct_btn_idcard_next,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:basicData];
    NSDictionary *credtiData = @{
        @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
        @"errorFlag" : kcredit_point_idcard,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
    NSDictionary *identityInfo = @{
        @"familyNameDesignation" : returnBeNil(self.model.familyNameDesignation),
        @"middle_name" : returnBeNil(self.model.middle_name),
        @"additionalName" : returnBeNil(self.model.additionalName),
        @"birthCelebrationDate" : returnBeNil(self.model.birthCelebrationDate),
        @"demographicSex" : returnBeNil(self.model.demographicSex),
        @"bankVerificationDetail" : returnBeNil(self.model.bankVerificationDetail),
    };
    NSDictionary *data = @{
        @"personalIdentityData" : identityInfo,
    };
    NSDictionary *dic = @{
        @"operationalTaskID" : returnBeNil(self.pageModel.operationalTaskID),
        @"identifierCode" : @"20002",
        @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
        @"data" : data,
    };
    [self.view showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/grantingCommit", CTPathTypeCredit, nil) parametersDic:dic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            [self requestResult];
        }
    }];
    NSDictionary *cacheDic = @{
        @"userGroup" : returnBeNil([CTUserManager shareManager].userModel.userGroup),
        @"crucialIdentifier" : @"personalProfileData",
        @"attributeCurrentValue" : [identityInfo mj_JSONString],
    };
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/setCreditResult", CTPathTypePost, nil) parametersDic:cacheDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        if (!isSuccess) {
        } else {
        }
    }];
}
- (void)requestResult {
    NSDictionary *paramDic = @{ @"operationalTaskID": returnBeNil(self.pageModel.operationalTaskID), @"requestIdentifier": @"20002" };
    [CTBaseRequest getRequestWithMethodName:CTPath(@"/grantingTaskState", CTPathTypeCredit, paramDic) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        if (!isSuccess) {
            [self.view dismissLoading];
        } else {
            if (responseObject[@"data"] != nil) {
                [self.view dismissLoading];
                NSDictionary *data = responseObject[@"data"];
                if ([data[@"identifierCode"] isEqualToString:@"70002"] && self.nextClickBlock) {
                    NSDictionary *credtiData = @{
                        @"tokenUniqueIdentifier"  : returnBeNil(self.pageModel.operationalTaskID),
                        @"errorFlag" : kpage_idcard_nextSucPoint,
                    };
                    [CTUploadManager ct_uploadType:CTUploadTypeCredit data:credtiData];
                    self.nextClickBlock();
                } else if ([data[@"identifierCode"] isEqualToString:@"70011"]) {
                    if (data[@"data"]) {
                        NSDictionary *content = data[@"data"];
                        if (content[@"otherUserGidList"]) {
                            NSArray *otherUserGidList = content[@"otherUserGidList"];
                            [self showBVNAlert:otherUserGidList.firstObject];
                        }
                    }
                } else {
                    [self.view showText:returnBeNil(data[@"textualCommunication"])];
                }
            } else {
                [self requestResult];
            }
        }
    }];
}
- (void)showBVNAlert:(NSString *)oldUserGid {
    __weak typeof(self) weakself = self;
    NSString *bvnStr = [NSString stringWithFormat:@"BVN:%@",returnBeNil(self.model.bankVerificationDetail)];
    TJAlertView *aAlertView = [TJAlertView alertWithTitle:@"Please confirm the ID number is correct." subTitle:bvnStr clickTitle:returnBeNil(self.model.bankVerificationDetail) clickSecond:@"" click:^(NSString * _Nonnull title) {
    }];
    TJAlertViewAction *aCancelAction = [TJAlertViewAction actionWithTitle:@"Correct" titleColor:[UIColor color161616] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction * _Nonnull action) {
        [weakself checkBvnRequest:oldUserGid];
    }];
    TJAlertViewAction *aSureAction = [TJAlertViewAction actionWithTitle:@"Re-enter" titleColor:[UIColor colorFF6C2E] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction *action) {
    }];
    [aAlertView doAddAction:aCancelAction];
    [aAlertView doAddAction:aSureAction];
    [aAlertView doShowAlertView];
    return;
}
- (void)checkBvnRequest:(NSString *)oldUserGid {
    NSDictionary *paramDic = @{ @"userGroup": returnBeNil([CTUserManager shareManager].userModel.userGroup),
                                @"previousUserGroup" : returnBeNil(oldUserGid),
                                @"bankVerificationNumber": returnBeNil(self.model.bankVerificationDetail) };
    [self.view showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/getOldPhoneAndAppName", CTPathTypePost, paramDic) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (isSuccess) {
            if (responseObject[@"matterContent"]) {
                [self showChangeBvnAlert:responseObject[@"matterContent"]];
            }
        } else {
        }
    }];
}
- (void)showChangeBvnAlert:(NSDictionary *)info {
    __weak typeof(self) weakself = self;
    NSString *tipStr = [NSString stringWithFormat:@"Sorry,this ID number has been used by phone number:%@",returnBeNil(info[@"wirelessDeviceNumber"])];
    NSString *contentStr = [NSString stringWithFormat:@"1.Please use %@ to log in\r\n2.If the original account can't be logged in,you can change the phone number of the original account to %@",returnBeNil(info[@"wirelessDeviceNumber"]),returnBeNil(info[@"bankVerificationNumber"])];
    TJAlertView *aAlertView = [TJAlertView alertWithTitle:tipStr subTitle:contentStr clickTitle:returnBeNil(info[@"wirelessDeviceNumber"]) clickSecond:returnBeNil(self.model.bankVerificationDetail) click:^(NSString * _Nonnull title) {
    }];
    TJAlertViewAction *aCancelAction = [TJAlertViewAction actionWithTitle:@"Log in to the original account" titleColor:[UIColor color161616] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction * _Nonnull action) {
        [[CTUserManager shareManager] userLogout];
    }];
    TJAlertViewAction *aSureAction = [TJAlertViewAction actionWithTitle:@"Change Original Number" titleColor:[UIColor colorFF6C2E] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction *action) {
        NSString *urlString = [NSString stringWithFormat:@"#/bvn_updatePhone?userGid=%@&inputBvn=%@", [CTUserManager shareManager].userModel.userGroup,self.model.bankVerificationDetail];
        NSString *fullUrl = [NSURL fullUrlStringForWeb:urlString];
        CTHomeVC *webVc = [[CTHomeVC alloc] initWithTitle:@"" gotoUrl:fullUrl];
        [webVc showLeftSingleBack];
        [weakself.navigationController pushViewController:webVc animated:YES];
    }];
    [aAlertView doAddAction:aCancelAction];
    [aAlertView doAddAction:aSureAction];
    [aAlertView doShowAlertView];
    return;
}
- (CTBasicModel *)model {
    if (!_model) {
        _model = [[CTBasicModel alloc] init];
    }
    return _model;
}
@end
